﻿namespace TransitDataParser
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Globalization;
    using ProtoBuf;
    using Caltrain.Model;

    class Program
    {
        static void Main(string[] args)
        {
            if (args[0] == "/?" || args[0] == "-?" || args[0] == "-h" || args[0] == "--help")
            {
                PrintUsage();
                return;
            }

            string gtfsDataDirectory = args[0];
            string outputFile = args[1];
            if (!Directory.Exists(gtfsDataDirectory))
            {
                Console.Write("Please provide valid directory name with GTFS files for Caltrain");
                return;
            }

            GTFSParser p = new GTFSParser(new CSVLineParser());
            Dictionary<string, Stop> stopsById = p.ParseStops(String.Format("{0}\\stops.txt", gtfsDataDirectory));
            Dictionary<string, Trip> tripsById = p.ParseTrips(String.Format("{0}\\trips.txt", gtfsDataDirectory));
            Dictionary<int, List<StopTime>> stopTimesByStopId = p.ParseStopTimes(String.Format("{0}\\stop_times.txt", gtfsDataDirectory), stopsById, tripsById);
            Dictionary<int, Trip> tripsByLookupId = tripsById.Values.ToDictionary<Trip, int>((t) => t.LookupId);
            Caltrain.Model.Calendar calendar = p.ParseCalendar(
                String.Format("{0}\\calendar.txt", gtfsDataDirectory), 
                String.Format("{0}\\calendar_dates.txt", gtfsDataDirectory));

            Schedule schedule = new Schedule()
            {
                StopsById = stopsById,
                TripsByLookupId = tripsByLookupId,
                StopTimesByStopId = stopTimesByStopId,
                Calendar = calendar
            };

            using (Stream stream = File.OpenWrite(outputFile))
            {
                Serializer.Serialize<Schedule>(stream, schedule);
            }
        }

        /// <summary>
        /// Prints usage information
        /// </summary>
        private static void PrintUsage()
        {
            Console.WriteLine(@"
Parses Caltrain GTFS Transit Data and converts it to form consumable by Caltrain Schedule WP7 app by serializing it using ProtoBuf-net.
Usage:
    TransitDataParser.exe <gtfs-dir> <outputfile>

Parameters:
    <gtfs-dir>: Directory with GTFS files
    <outputfile>: Output file

Example:
    TransitDataParser.exe ""C:\Users\gokult\Projects\CaltrainSchedule\LatestGTFSData"" ""C:\Users\gokult\Projects\CaltrainSchedule\Source\schedule""
");
            return;
        }
    }
}
